from flask import Blueprint, request, jsonify

from module_admin.entity.do.base import db
from module_admin.entity.do.file import File
from module_admin.entity.do.submission import Submission

from module_admin.utils.http import fail_api, success_api, table_api
from module_admin.utils.validate import str_escape

submission = Blueprint('submission', __name__)


@submission.post('/add_submission')
def add_submission():
    req_json = request.get_json(force=True)
    submission_file = str_escape(req_json.get('submission_file'))
    grade = req_json.get('grade')
    assignment_id = req_json.get('assignment_id')
    student_id = req_json.get('student_id')

    if not submission_file or not assignment_id or not student_id:
        return fail_api(msg="提交文件路径、作业ID和学生ID不得为空")

    submission = Submission(
        submission_file=submission_file,
        grade=grade,
        assignment_id=assignment_id,
        student_id=student_id
    )
    db.session.add(submission)
    db.session.commit()
    return success_api(msg="作业提交成功")


@submission.get('/submission_list')
def get_all_submissions():
    # 查询所有作业提交记录
    submissions = Submission.query.all()

    # 构建返回数据
    submission_list = [
        {
            "id": submission.id,
            "submission_file": submission.submission_file,
            "grade": submission.grade,
            "assignment_id": submission.assignment_id,
            "student_id": submission.student_id,
        }
        for submission in submissions
    ]

    return table_api(data=submission_list, msg="获取作业提交列表成功")


@submission.post('/edit_submission/<int:submission_id>')
def edit_submission(submission_id):
    req_json = request.get_json(force=True)
    new_submission_file = str_escape(req_json.get('submission_file'))
    new_grade = req_json.get('grade')
    new_assignment_id = req_json.get('assignment_id')
    new_student_id = req_json.get('student_id')

    # 查找指定作业提交记录
    submission = Submission.query.filter_by(id=submission_id).first()

    if not submission:
        return fail_api(msg="作业提交记录不存在")

    # 更新提交记录信息
    if new_submission_file:
        submission.submission_file = new_submission_file
    if new_grade is not None:
        submission.grade = new_grade
    if new_assignment_id:
        submission.assignment_id = new_assignment_id
    if new_student_id:
        submission.student_id = new_student_id

    db.session.commit()
    return success_api(msg="作业提交记录编辑成功")


@submission.get('/delete_submission/<int:submission_id>')
def delete_submission(submission_id):
    # 查找指定作业提交记录
    submission = Submission.query.filter_by(id=submission_id).first()

    if not submission:
        return fail_api(msg="作业提交记录不存在")

    # 删除提交记录
    db.session.delete(submission)
    db.session.commit()

    return success_api(msg="作业提交记录删除成功")



